<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChRoomPresetMapper;
use App\CustHub\Model\ChRoomTag;
use Mine\Abstracts\AbstractService;
use Mine\MineModel;

class ChRoomPresetService extends AbstractService
{
    public $mapper;

    public function __construct(ChRoomPresetMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * 新增数据.
     */
    public function save(array $data): mixed
    {
        $data = $this->changeData($data);
        return $this->mapper->save($data);
    }

    /**
     * 读取一条数据.
     */
    public function read(mixed $id, array $column = ['*']): ?MineModel
    {
        $info = $this->mapper->read($id, $column);

        if(!empty($info)){
            $roomTags = $info->room_tags;
            if(!empty($roomTags)){
                $roomTagsList = ChRoomTag::query()
                    ->select(['id','name'])
                    ->whereIn('id',$roomTags)
                    ->get();
            }else{
                $roomTagsList = [];
            }
            $info->room_tags_list = $roomTagsList;
        }

        return $info;
    }


    /**
     * 更新一条数据.
     */
    public function update(mixed $id, array $data): bool
    {
        $data = $this->changeData($data);
        return $this->mapper->update($id, $data);
    }
    private function changeData(array $data): array
    {
        $fields = [
            'room_name_keywords',
            'room_tags',
            'role'
        ];
        foreach ($fields as $field){
            if(!empty($data[$field])){
                $data[$field] = json_decode($data[$field],true);
            }else{
                $data[$field] = '';
            }
        }
        return $data;
    }
}